import { axios,regetToken, prd_rls_idCard } from 'utils/util';
import { TypeOf } from './funcs'

const checkUrl = (url, checkLogout) => {
  const ignoreUrls = ['auth/login', 'auth/refresh_token'];
  if (checkLogout) {
    ignoreUrls.push('/auth/logout');
  }
  for (let i = ignoreUrls.length - 1; i >= 0; i--) {
    if (url.indexOf(ignoreUrls[i]) > -1) {
      return true;
    }
  }
  return false;
}
axios.interceptors.response.use(
  response => {
		if(response && response.code === 200 || response.errorCode === '0' || TypeOf(response) === 'ArrayBuffer'){
			regetToken()
			return response;
		}else if(response && response.code !== 200){
			if(response.code === 20005){
				MessageBox.alert('登录信息已过期，请重新登录?', '提示', {
          confirmButtonText: '确定',
          type: 'warning'
        }).then(() => {
          window.location.href = './login.html';
        }).catch(() => {
          window.location.href = './login.html';
        });
			}else if(response.code === 7001){
				return response;
			}else {
				Message.error({ message: response.message, duration: 2000 });
			}
		}
		return response;
  }, error => {
    if (error.response) {
			console.log('响应错误error', error);
      /* if (error.response.status == 504 || error.response.status == 404 ) {
      } else  */
      let data = error.response.data;
      // 先排除ecif
      if (error.response.status == 401 && !checkUrl(error.response.config.url, true)) {
        if (!error.response.config.headers['HasRegetToken']) {
          return regetToken(error.response.config);
        }
        // 已重新获取token的不做任何操作，直接返回
      } else if (error.response.status == 426) {
        // 清空token
        cacheUtil.setCookies('Authorization', '');
        // 直接退出
        MessageBox.alert('登录信息已过期，请重新登录?', '提示', {
          confirmButtonText: '确定',
          type: 'warning'
        }).then(() => {
          window.location.href = './login.html';
        }).catch(() => {
          window.location.href = './login.html';
        });
        return Promise.reject(error);
      } else if (error.response.status == 403) {
        let errorMsg = '权限不足,请联系管理员!';
        if (data && data.message) {
          errorMsg = data.message;
        }
        Message.error({ showClose: true, message: errorMsg });
      } else {
        if (data && !data.message) {
          //过滤html标签
          // error.response.data = error.response.data.replace(/<[^<>]+>/g, '');
          error.response.data = { message: 'Error：' + error.response.status + ' ' + error.response.statusText };
        }
      }
    } else {
      let msg = error.message || '请求失败，请稍后重试!';
      /* Message.error({
        showClose: true,
        message: msg
      }); */
      if (msg.indexOf('timeout') > -1) {
        msg = '请求超时，请稍后重试！';
      }
      error.message = msg;
    }
    //检验是否为ArrayBuffer
    let objType = TypeOf(error.response.data);
    if (error.response && (objType === 'ArrayBuffer' || objType === 'Blob')) {
      return Promise.reject(error);
    }
    return Promise.resolve(error.response ? error.response.data : error);
  }
);
const post = function (url, data = {}, succFun, errorFun) {
  return axios.post(url, data)
    .then(response => {
      if ((response.code === 200 || response.errorCode == '0') && succFun) {
				regetToken()
        succFun(response);
      } else if (errorFun) {
        errorFun(response || {message: '请求失败，请稍后重试!'});
      }
    }, err => {
      errorFun && errorFun(err.response ? err.response : err)
  })
}
const get = function (url, data = {}, succFun, errorFun) {
  return axios.get(url, {
    params: data
  })
    .then(response => {
      // update By Liaolk 2021/11/23; 不清楚success有没有用，就先保留
      if ((response.success || (response.errorCode && response.errorCode == '0')) && succFun) {
        succFun(response);
      } else if (errorFun) {
        // console.log(response)
        errorFun(response || {message: '请求失败，请稍后重试!'});
      }
    }, err => {
      errorFun && errorFun(err.response ? err.response : err)
    })
}

//下载文件
const postFile = (url, data = {}, succFun, errorFun, config = { responseType: 'arraybuffer', dataType: 'binary' }) => {
  return axios.post(url, data, config)
    .then(response => {
      //防止超时返回为空，error数据进入，下载空文件
      if (TypeOf(response) === 'ArrayBuffer') {
        succFun && succFun(response);
      } else {
        errorFun && errorFun(response);
      }
    }, err => {
      let enc = new TextDecoder('utf-8'),
        res = null;
      if (err.response && err.response.data) {
        res = JSON.parse(enc.decode(new Uint8Array(err.response.data))); //转化成json对象
      }
      errorFun && errorFun(res ? res : err);
    })
}
export { post, get, postFile, axios};